package com.wmsafe.common.utils;

import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 异步删除文件
 */
public class FileUtils {
    private static final int MAX_RETRIES = 15;//最大重试次数

    public static CompletableFuture<Boolean> deleteFileAsync(File file) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        return CompletableFuture.supplyAsync(() -> deleteFile(file), executorService);
    }

    private static boolean deleteFile(File file) {
        boolean deleted = false;
        int retryCount = 0;

        while (!deleted && retryCount < MAX_RETRIES) {
            try {
                if (file.delete()) {
                    deleted = true;
                } else {
                    retryCount++;
                    TimeUnit.SECONDS.sleep(1); // 延迟1秒后重试
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (!deleted) {
            System.out.println("无法删除文件：" + file.getName());
        }

        return deleted;
    }
}
